# Computations
import numpy as np
import pandas as pd
import pickle
# sklearn
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import GridSearchCV, RandomizedSearchCV, cross_val_score, KFold, StratifiedShuffleSplit
from sklearn import metrics
from sklearn.feature_selection import RFE
from sklearn.ensemble import GradientBoostingClassifier
# Visualisation libraries
## Text
from colorama import Fore, Back, Style
from IPython.display import Image, display, Markdown, Latex, clear_output
## progressbar
import progressbar
## plotly
from plotly.offline import init_notebook_mode, iplot
import plotly.graph_objs as go
import plotly.offline as py
from plotly.subplots import make_subplots
import plotly.express as px
## seaborn
import seaborn as sns
## matplotlib
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse, Polygon
from matplotlib.font_manager import FontProperties
import matplotlib.colors as mcolors
plt.style.use('seaborn-whitegrid')
plt.rcParams['axes.labelsize'] = 14
plt.rcParams['xtick.labelsize'] = 12
plt.rcParams['ytick.labelsize'] = 12
plt.rcParams['text.color'] = 'k'
%matplotlib inline
import warnings
warnings.filterwarnings("ignore")
In this article, we analyze the UCI Statlog (german credit data) from Kaggle.com.
The original dataset contains 1000 entries with 20 categorial/symbolic attributes prepared by Prof. Hofmann. In this dataset, each entry represents a person who takes a credit by a bank. Each person is classified as good or bad credit risks according to the set of attributes. The link to the original dataset can be found below.
It is almost impossible to understand the original dataset due to its complicated system of categories and symbols. Thus, I wrote a small Python script to convert it into a readable CSV file. Several columns are simply ignored, because in my opinion either they are not important or their descriptions are obscure. The selected attributes are:
Path = 'Statlog_Dataset/german_credit_data.csv'
def Header(Text, L = 100, C = 'Blue', T = 'White'):
BACK = {'Black': Back.BLACK, 'Red':Back.RED, 'Green':Back.GREEN, 'Yellow': Back.YELLOW, 'Blue': Back.BLUE,
'Magenta':Back.MAGENTA, 'Cyan': Back.CYAN}
FORE = {'Black': Fore.BLACK, 'Red':Fore.RED, 'Green':Fore.GREEN, 'Yellow':Fore.YELLOW, 'Blue':Fore.BLUE,
'Magenta':Fore.MAGENTA, 'Cyan':Fore.CYAN, 'White': Fore.WHITE}
print(BACK[C] + FORE[T] + Style.NORMAL + Text + Style.RESET_ALL + ' ' + FORE[C] +
Style.NORMAL + (L- len(Text) - 1)*'=' + Style.RESET_ALL)
def Line(L=100, C = 'Blue'):
FORE = {'Black': Fore.BLACK, 'Red':Fore.RED, 'Green':Fore.GREEN, 'Yellow':Fore.YELLOW, 'Blue':Fore.BLUE,
'Magenta':Fore.MAGENTA, 'Cyan':Fore.CYAN, 'White': Fore.WHITE}
print(FORE[C] + Style.NORMAL + L*'=' + Style.RESET_ALL)
def Search_List(Key, List): return [s for s in List if Key in s]
Data = pd.read_csv(Path.split(".")[0]+'_STD.csv')
Header('Standardized Dataset:')
display(Data.head())
display(pd.DataFrame({'Number of Instances': [Data.shape[0]], 'Number of Attributes': [Data.shape[1]]}).style.hide_index())
# Dictionaries
with open(Path.split(".")[0] + '_Feat_Dict.pkl', 'rb') as fp:
Feat_Dict = pickle.load(fp)
Standardized Dataset: ==============================================================================
| Age | Sex | Job | Housing | Saving Accounts | Checking Account | Credit Amount | Duration | Risk | Business | Car | Domestic Appliances | Education | Furniture/Equipment | Radio/TV | Repairs | Vacation/Others | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 2.830066 | 0.670280 | 0.146949 | 0.585603 | -1.231393 | -0.001045 | -0.745131 | -1.885247 | 1 | -0.327749 | -0.712949 | -0.110208 | -0.250398 | -0.470108 | 1.603567 | -0.149983 | -0.110208 |
| 1 | -1.016875 | -1.491914 | 0.146949 | 0.585603 | -0.196609 | 1.044372 | 0.949817 | 0.439349 | 0 | -0.327749 | -0.712949 | -0.110208 | -0.250398 | -0.470108 | 1.603567 | -0.149983 | -0.110208 |
| 2 | 1.547753 | 0.670280 | -1.383771 | 0.585603 | -0.196609 | -1.046463 | -0.416562 | 1.214214 | 1 | -0.327749 | -0.712949 | -0.110208 | 3.993639 | -0.470108 | -0.623610 | -0.149983 | -0.110208 |
| 3 | 0.265439 | 0.670280 | 0.146949 | -2.379476 | -0.196609 | -0.001045 | 1.634247 | 0.439349 | 1 | -0.327749 | -0.712949 | -0.110208 | -0.250398 | 2.127172 | -0.623610 | -0.149983 | -0.110208 |
| 4 | 1.547753 | 0.670280 | 0.146949 | -2.379476 | -0.196609 | -0.001045 | 0.566664 | -0.335517 | 0 | -0.327749 | 1.402626 | -0.110208 | -0.250398 | -0.470108 | -0.623610 | -0.149983 | -0.110208 |
| Number of Instances | Number of Attributes |
|---|---|
| 1000 | 17 |
Target = 'Risk'
X = Data.drop(columns = [Target])
y = Data[Target]
Labels = list(Feat_Dict[Target].keys())
def Dist_Table(Inp, Target):
Table = Inp[Target].value_counts().to_frame('Count').reset_index(drop = False).rename(columns = {'index':Target})
Table[Target] = Table[Target].replace(dict(zip([0,1],Labels)))
Table['Percentage'] = np.round(100*(Table['Count']/Table['Count'].sum()),2)
return Table
def Dist_Plot(Table, Target, PieColors = ['SeaGreen', 'FireBrick'], TableColors = ['Navy','White']):
fig = make_subplots(rows=1, cols=2, horizontal_spacing = 0.02, column_widths=[0.6, 0.4],
specs=[[{"type": "table"},{"type": "pie"}]])
# Right
fig.add_trace(go.Pie(labels=Table[Target].values, values=Table['Count'].values, pull=[0, 0.1], textfont=dict(size=16),
marker=dict(colors = PieColors, line=dict(color='black', width=1))), row=1, col=2)
fig.update_traces(hole=.5)
fig.update_layout(height = 400, legend=dict(orientation="v"), legend_title_text= Target)
# Left
T = Table.copy()
T['Percentage'] = T['Percentage'].map(lambda x: '%%%.2f' % x)
Temp = []
for i in T.columns:
Temp.append(T.loc[:,i].values)
fig.add_trace(go.Table(header=dict(values = list(Table.columns), line_color='darkslategray',
fill_color= TableColors[0], align=['center','center'],
font=dict(color='white', size=12), height=25), columnwidth = [0.4, 0.2, 0.2],
cells=dict(values=Temp, line_color='darkslategray',
fill=dict(color= [TableColors[1], TableColors[1]]),
align=['center', 'center'], font_size=12, height=20)), 1, 1)
fig.update_layout(title={'text': '<b>' + Target + ' Distribution' + '<b>', 'x':0.5,
'y':0.90, 'xanchor': 'center', 'yanchor': 'top'})
fig.show()
Table = Dist_Table(Inp = Data, Target = Target)
Dist_Plot(Table, Target = Target, PieColors = ['LightGreen', 'DarkOrange'], TableColors = ['DarkRed','MistyRose'])
StratifiedKFold is a variation of k-fold which returns stratified folds: each set contains approximately the same percentage of samples of each target class as the complete set.
Test_Size = 0.3
sss = StratifiedShuffleSplit(n_splits=1, test_size=Test_Size, random_state=42)
_ = sss.get_n_splits(X, y)
for train_index, test_index in sss.split(X, y):
# X
if isinstance(X, pd.DataFrame):
X_train, X_test = X.loc[train_index], X.loc[test_index]
else:
X_train, X_test = X[train_index], X[test_index]
# y
if isinstance(y, pd.Series):
y_train, y_test = y[train_index], y[test_index]
else:
y_train, y_test = y[train_index], y[test_index]
del sss
def Train_Test_Dist(X_train, y_train, X_test, y_test, PieColors = ['FireBrick','SeaGreen'], TableColors = ['Navy','White']):
def ToSeries(x):
if not isinstance(x, pd.Series):
Out = pd.Series(x)
else:
Out = x.copy()
return Out
fig = make_subplots(rows=1, cols=3, specs=[[{"type": "table"},{'type':'domain'}, {'type':'domain'}]])
fig.add_trace(go.Pie(labels=Labels, values=ToSeries(y_train).value_counts().values, pull=[0, 0.1], name= 'Train Set',
textfont=dict(size=16), marker= dict(colors = PieColors, line=dict(color='black', width=1))), 1, 2)
fig.add_trace(go.Pie(labels=Labels, values=ToSeries(y_test).value_counts().values, pull=[0, 0.1], name= 'Test Set',
textfont=dict(size=16), marker= dict(colors = PieColors, line=dict(color='black', width=1))), 1, 3)
fig.update_traces(hole=.5)
fig.update_layout(height = 400, legend=dict(orientation="v"), legend_title_text= Target,
annotations=[dict(text= '<b>' + 'Train<br>Set' + '<b>', x=0.49, y=0.5, font_size=14, showarrow=False),
dict(text= '<b>' + 'Test<br>Set' + '<b>', x=0.88, y=0.5, font_size=14, showarrow=False)],
title={'text': '<b>' + 'Train and Test Distribution' + '<b>', 'x':0.48, 'y': .83,
'xanchor': 'center', 'yanchor': 'top'})
# Table
Table = pd.DataFrame(data={'Set':['X_train','X_test','y_train','y_test'],
'Shape':[X_train.shape, X_test.shape, y_train.shape, y_test.shape]}).astype(str)
T = Table.copy()
Temp = []
for i in T.columns:
Temp.append(T.loc[:,i].values)
fig.add_trace(go.Table(header=dict(values = list(Table.columns), line_color='darkslategray',
fill_color= TableColors[0], align=['center','center'],
font=dict(color='white', size=12), height=25), columnwidth = [0.2, 0.2, 0.2],
cells=dict(values=Temp, line_color='darkslategray',
fill=dict(color= [TableColors[1], TableColors[1]]),
align=['center', 'center'], font_size=12, height=20)), 1, 1)
fig.show()
Train_Test_Dist(X_train, y_train, X_test, y_test, PieColors = ['LightGreen', 'DarkOrange'],
TableColors = ['DarkRed','MistyRose'])
Gradient Boosting Classifier (GBC) optimizes a model in several stages using differentiable loss function. See sklearn.ensemble.GradientBoostingClassifier for more details.
def Header(Text, L = 100, C = 'Blue', T = 'White'):
BACK = {'Black': Back.BLACK, 'Red':Back.RED, 'Green':Back.GREEN, 'Yellow': Back.YELLOW, 'Blue': Back.BLUE,
'Magenta':Back.MAGENTA, 'Cyan': Back.CYAN}
FORE = {'Black': Fore.BLACK, 'Red':Fore.RED, 'Green':Fore.GREEN, 'Yellow':Fore.YELLOW, 'Blue':Fore.BLUE,
'Magenta':Fore.MAGENTA, 'Cyan':Fore.CYAN, 'White': Fore.WHITE}
print(BACK[C] + FORE[T] + Style.NORMAL + Text + Style.RESET_ALL + ' ' + FORE[C] +
Style.NORMAL + (L- len(Text) - 1)*'=' + Style.RESET_ALL)
def Line(L=100, C = 'Blue'):
FORE = {'Black': Fore.BLACK, 'Red':Fore.RED, 'Green':Fore.GREEN, 'Yellow':Fore.YELLOW, 'Blue':Fore.BLUE,
'Magenta':Fore.MAGENTA, 'Cyan':Fore.CYAN, 'White': Fore.WHITE}
print(FORE[C] + Style.NORMAL + L*'=' + Style.RESET_ALL)
def Search_List(Key, List): return [s for s in List if Key in s]
def Best_Parm(model, param_dist, Top = None, X = X, y = y, n_splits = 20, scoring = 'precision', H = 600, titleY = .95):
grid = RandomizedSearchCV(estimator = model, param_distributions = param_dist,
cv = StratifiedShuffleSplit(n_splits=n_splits, test_size=Test_Size, random_state=42),
n_iter = int(1e3), scoring = scoring, error_score = 0, verbose = 0,
n_jobs = 10, return_train_score = True)
_ = grid.fit(X, y)
Table = Grid_Table(grid)
if Top == None:
Top = Table.shape[0]
Table = Table.iloc[:Top,:]
# Table
T = Table.copy()
T['Train Score'] = T['Mean Train Score'].map(lambda x: ('%.2e' % x))+ ' ± ' +T['STD Train Score'].map(lambda x: ('%.2e' % x))
T['Test Score'] = T['Mean Test Score'].map(lambda x: ('%.2e' % x))+ ' ± ' +T['STD Test Score'].map(lambda x: ('%.2e' % x))
T['Fit Time'] = T['Mean Fit Time'].map(lambda x: ('%.2e' % x))+ ' ± ' +T['STD Fit Time'].map(lambda x: ('%.2e' % x))
T = T.drop(columns = ['Mean Train Score','STD Train Score','Mean Test Score','STD Test Score','Mean Fit Time','STD Fit Time'])
display(T.head(Top).style.hide_index().background_gradient(subset= ['Rank Test Score'],
cmap='GnBu').\
set_properties(subset=['Params'], **{'background-color': 'Indigo', 'color': 'White'}).\
set_properties(subset=['Train Score'], **{'background-color': 'HoneyDew', 'color': 'Black'}).\
set_properties(subset=['Test Score'], **{'background-color': 'Azure', 'color': 'Black'}).\
set_properties(subset=['Fit Time'], **{'background-color': 'Linen', 'color': 'Black'}))
# Plot
Grid_Performance_Plot(Table, n_splits = n_splits, H = H, titleY = titleY)
return grid
def Grid_Table(grid):
Table = pd.DataFrame({'Rank Test Score': grid.cv_results_['rank_test_score'],
'Params':[str(s).replace('{', '').replace('}', '').\
replace("'", '') for s in grid.cv_results_['params']],
# Train
'Mean Train Score': grid.cv_results_['mean_train_score'],
'STD Train Score': grid.cv_results_['std_train_score'],
# Test
'Mean Test Score': grid.cv_results_['mean_test_score'],
'STD Test Score': grid.cv_results_['std_test_score'],
# Fit time
'Mean Fit Time': grid.cv_results_['mean_fit_time'],
'STD Fit Time': grid.cv_results_['std_fit_time']})
Table = Table.sort_values('Rank Test Score').reset_index(drop = True)
return Table
def Grid_Performance_Plot(Table, n_splits, H = 550, titleY =.95):
Temp = Table['Mean Train Score']-Table['STD Train Score']
Temp = np.append(Temp, Table['Mean Test Score']-Table['STD Test Score'])
L = np.floor((Temp*100- Temp)).min()/100
Temp = Table['Mean Train Score']+Table['STD Train Score']
Temp = np.append(Temp, Table['Mean Test Score']+Table['STD Test Score'])
R = np.ceil((Temp*100 + Temp)).max()/100
fig = make_subplots(rows=1, cols=2, horizontal_spacing = 0.02, shared_yaxes=True,
subplot_titles=('<b>' + 'Train Set' + '<b>', '<b>' + 'Test Set' + '<b>'))
fig.add_trace(go.Scatter(x= Table['Params'], y= Table['Mean Train Score'], showlegend=False, marker_color= 'SeaGreen',
error_y=dict(type='data',array=Table['STD Train Score'], visible=True)), 1, 1)
fig.add_trace(go.Scatter(x= Table['Params'], y= Table['Mean Test Score'], showlegend=False, marker_color= 'RoyalBlue',
error_y=dict(type='data',array= Table['STD Test Score'], visible=True)), 1, 2)
fig.update_xaxes(showline=True, linewidth=1, linecolor='Lightgray', mirror=True,
zeroline=False, zerolinewidth=1, zerolinecolor='Black',
showgrid=False, gridwidth=1, gridcolor='Lightgray')
fig.update_yaxes(showline=True, linewidth=1, linecolor='Lightgray', mirror=True,
zeroline=True, zerolinewidth=1, zerolinecolor='Black',
showgrid=True, gridwidth=1, gridcolor='Lightgray', range= [L, R])
fig.update_yaxes(title_text="Mean Score", row=1, col=1)
fig.update_layout(plot_bgcolor= 'white', width = 980, height = H,
title={'text': '<b>' + 'RandomizedSearchCV with %i-fold cross validation' % n_splits + '<b>',
'x':0.5, 'y':titleY, 'xanchor': 'center', 'yanchor': 'top'})
fig.show()
def Stratified_CV_Scoring(model, X = X, y = y, n_splits = 10):
sss = StratifiedShuffleSplit(n_splits = n_splits, test_size=Test_Size, random_state=42)
if isinstance(X, pd.DataFrame):
X = X.values
if isinstance(y, pd.Series):
y = y.values
_ = sss.get_n_splits(X, y)
Reports_Train = []
Reports_Test = []
CM_Train = []
CM_Test = []
for train_index, test_index in sss.split(X, y):
X_train, X_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]
_ = model.fit(X_train,y_train)
# Train
y_pred = model.predict(X_train)
R = pd.DataFrame(metrics.classification_report(y_train, y_pred, target_names=Labels, output_dict=True)).T
Reports_Train.append(R.values)
CM_Train.append(metrics.confusion_matrix(y_train, y_pred))
# Test
y_pred = model.predict(X_test)
R = pd.DataFrame(metrics.classification_report(y_test, y_pred, target_names=Labels, output_dict=True)).T
Reports_Test.append(R.values)
CM_Test.append(metrics.confusion_matrix(y_test, y_pred))
# Train
ALL = Reports_Train[0].ravel()
CM = CM_Train[0].ravel()
for i in range(1, len(Reports_Train)):
ALL = np.vstack((ALL, Reports_Train[i].ravel()))
CM = np.vstack((CM, CM_Train[i].ravel()))
Mean = pd.DataFrame(ALL.mean(axis = 0).reshape(R.shape), index = R.index, columns = R.columns)
STD = pd.DataFrame(ALL.std(axis = 0).reshape(R.shape), index = R.index, columns = R.columns)
Reports_Train = Mean.applymap(lambda x: ('%.4f' % x))+ ' ± ' +STD.applymap(lambda x: ('%.4f' % x))
CM_Train = CM.mean(axis = 0).reshape(CM_Train[0].shape).round(0).astype(int)
del ALL, Mean, STD
# Test
ALL = Reports_Test[0].ravel()
CM = CM_Test[0].ravel()
for i in range(1, len(Reports_Test)):
ALL = np.vstack((ALL, Reports_Test[i].ravel()))
CM = np.vstack((CM, CM_Test[i].ravel()))
Mean = pd.DataFrame(ALL.mean(axis = 0).reshape(R.shape), index = R.index, columns = R.columns)
STD = pd.DataFrame(ALL.std(axis = 0).reshape(R.shape), index = R.index, columns = R.columns)
Reports_Test = Mean.applymap(lambda x: ('%.4f' % x))+ ' ± ' +STD.applymap(lambda x: ('%.4f' % x))
CM_Test = CM.mean(axis = 0).reshape(CM_Test[0].shape).round(0).astype(int)
del ALL, Mean, STD
Reports_Train = Reports_Train.reset_index().rename(columns ={'index': 'Train Set (CV = % i)' % n_splits})
Reports_Test = Reports_Test.reset_index().rename(columns ={'index': 'Test Set (CV = % i)' % n_splits})
return Reports_Train, Reports_Test, CM_Train, CM_Test
def Confusion_Mat(CM_Train, CM_Test, n_splits = 10):
# Font
font = FontProperties()
font.set_weight('bold')
Titles = ['Train Set (CV = % i)' % n_splits, 'Test Set (CV = % i)' % n_splits]
CM = [CM_Train, CM_Test]
Cmap = ['Greens', 'YlGn','Blues', 'PuBu']
for i in range(2):
fig, ax = plt.subplots(1, 2, figsize=(12, 4))
fig.suptitle(Titles[i], fontproperties=font, fontsize = 16)
_ = sns.heatmap(CM[i], annot=True, annot_kws={"size": 14}, cmap=Cmap[2*i], ax = ax[0],
linewidths = 0.2, cbar_kws={"shrink": 1})
_ = ax[0].set_title('Confusion Matrix');
_ = sns.heatmap(CM[i].astype('float') / CM[i].sum(axis=1)[:, np.newaxis],
annot=True, annot_kws={"size": 14}, cmap=Cmap[2*i+1], ax = ax[1],
linewidths = 0.2, vmin=0, vmax=1, cbar_kws={"shrink": 1})
_ = ax[1].set_title('Normalized Confusion Matrix');
for a in ax:
_ = a.set_xlabel('Predicted labels')
_ = a.set_ylabel('True labels');
_ = a.xaxis.set_ticklabels(Labels)
_ = a.yaxis.set_ticklabels(Labels)
_ = a.set_aspect(1)
Some of the metrics that we use here to mesure the accuracy: \begin{align} \text{Confusion Matrix} = \begin{bmatrix}T_p & F_p\\ F_n & T_n\end{bmatrix}. \end{align}
where $T_p$, $T_n$, $F_p$, and $F_n$ represent true positive, true negative, false positive, and false negative, respectively.
\begin{align} \text{Precision} &= \frac{T_{p}}{T_{p} + F_{p}},\\ \text{Recall} &= \frac{T_{p}}{T_{p} + F_{n}},\\ \text{F1} &= \frac{2 \times \text{Precision} \times \text{Recall}}{\text{Precision} + \text{Recall}}\\ \text{Balanced-Accuracy (bACC)} &= \frac{1}{2}\left( \frac{T_{p}}{T_{p} + F_{n}} + \frac{T_{n}}{T_{n} + F_{p}}\right ) \end{align}The accuracy can be a misleading metric for imbalanced data sets. In these cases, a balanced accuracy (bACC) [4] is recommended that normalizes true positive and true negative predictions by the number of positive and negative samples, respectively, and divides their sum by two.
Header('Gradient Boosting Classifier with Default Parameters')
n_splits = 20
GBC= GradientBoostingClassifier()
print('Default Parameters = %s' % GBC.get_params(deep=True))
_ = GBC.fit(X_train, y_train)
Reports_Train, Reports_Test, CM_Train, CM_Test = Stratified_CV_Scoring(GBC, X = X, y = y, n_splits = n_splits)
display(Reports_Train.style.hide_index().set_properties(**{'background-color': 'HoneyDew', 'color': 'Black'}).\
set_properties(subset=['Train Set (CV = % i)' % n_splits], **{'background-color': 'SeaGreen', 'color': 'White'}))
display(Reports_Test.style.hide_index().set_properties(**{'background-color': 'Azure', 'color': 'Black'}).\
set_properties(subset=['Test Set (CV = % i)' % n_splits], **{'background-color': 'RoyalBlue', 'color': 'White'}))
Confusion_Mat(CM_Train, CM_Test, n_splits = n_splits)
Header('Train Set', C = 'Green')
tn, fp, fn, tp = CM_Train.ravel()
Precision = tp/(tp+fp)
Recall = tp/(tp + fn)
TPR = tp/(tp +fn)
TNR = tn/(tn +fp)
BA = (TPR + TNR)/2
print('Precision (Train) = %.2f' % Precision)
print('Recall (Train) = %.2f' % Recall)
print('TPR (Train) = %.2f' % TPR)
print('TNR (Train) = %.2f' % TNR)
print('Balanced Accuracy (Train) = %.2f' % BA)
Header('Test Set')
tn, fp, fn, tp = CM_Test.ravel()
Precision = tp/(tp+fp)
Recall = tp/(tp + fn)
TPR = tp/(tp +fn)
TNR = tn/(tn +fp)
BA = (TPR + TNR)/2
PPCR = (tp + fp)/(tp + fp + tn+ fn)
print('Precision (Test) = %.2f' % Precision)
print('Recall (Test) = %.2f' % Recall)
print('TPR (Test) = %.2f' % TPR)
print('TNR (Test) = %.2f' % TNR)
print('Balanced Accuracy (Test) = %.2f' % BA)
del tn, fp, fn, tp, Precision, Recall, TPR, TNR, BA
Line()
Gradient Boosting Classifier with Default Parameters =============================================== Default Parameters = {'ccp_alpha': 0.0, 'criterion': 'friedman_mse', 'init': None, 'learning_rate': 0.1, 'loss': 'deviance', 'max_depth': 3, 'max_features': None, 'max_leaf_nodes': None, 'min_impurity_decrease': 0.0, 'min_impurity_split': None, 'min_samples_leaf': 1, 'min_samples_split': 2, 'min_weight_fraction_leaf': 0.0, 'n_estimators': 100, 'n_iter_no_change': None, 'random_state': None, 'subsample': 1.0, 'tol': 0.0001, 'validation_fraction': 0.1, 'verbose': 0, 'warm_start': False}
| Train Set (CV = 20) | precision | recall | f1-score | support |
|---|---|---|---|---|
| Bad | 0.8766 ± 0.0240 | 0.6600 ± 0.0321 | 0.7525 ± 0.0237 | 210.0000 ± 0.0000 |
| Good | 0.8684 ± 0.0108 | 0.9600 ± 0.0090 | 0.9118 ± 0.0072 | 490.0000 ± 0.0000 |
| accuracy | 0.8700 ± 0.0109 | 0.8700 ± 0.0109 | 0.8700 ± 0.0109 | 0.8700 ± 0.0109 |
| macro avg | 0.8725 ± 0.0142 | 0.8100 ± 0.0162 | 0.8322 ± 0.0153 | 700.0000 ± 0.0000 |
| weighted avg | 0.8708 ± 0.0115 | 0.8700 ± 0.0109 | 0.8640 ± 0.0120 | 700.0000 ± 0.0000 |
| Test Set (CV = 20) | precision | recall | f1-score | support |
|---|---|---|---|---|
| Bad | 0.5727 ± 0.0548 | 0.3917 ± 0.0455 | 0.4632 ± 0.0402 | 90.0000 ± 0.0000 |
| Good | 0.7702 ± 0.0128 | 0.8729 ± 0.0284 | 0.8181 ± 0.0153 | 210.0000 ± 0.0000 |
| accuracy | 0.7285 ± 0.0205 | 0.7285 ± 0.0205 | 0.7285 ± 0.0205 | 0.7285 ± 0.0205 |
| macro avg | 0.6714 ± 0.0318 | 0.6323 ± 0.0230 | 0.6406 ± 0.0254 | 300.0000 ± 0.0000 |
| weighted avg | 0.7109 ± 0.0231 | 0.7285 ± 0.0205 | 0.7116 ± 0.0203 | 300.0000 ± 0.0000 |
Train Set ========================================================================================== Precision (Train) = 0.87 Recall (Train) = 0.96 TPR (Train) = 0.96 TNR (Train) = 0.66 Balanced Accuracy (Train) = 0.81 Test Set =========================================================================================== Precision (Test) = 0.77 Recall (Test) = 0.87 TPR (Test) = 0.87 TNR (Test) = 0.39 Balanced Accuracy (Test) = 0.63 ====================================================================================================
In order to find the parameters for our model, we can sue RandomizedSearchCV. Here, we have defined a function Best_Parm to find the best parameters.
GBC= GradientBoostingClassifier()
param_dist = dict(loss = ['deviance', 'exponential'],
learning_rate = [.8, .9, 1.0],
n_estimators= [100, 200, 1000],
max_leaf_nodes = [None, 2, 3])
Header('Gradient Boosting Classifier with the Best Parameters')
grid = Best_Parm(model = GBC, param_dist = param_dist, Top = 20, H = 750, titleY =.96)
Gradient Boosting Classifier with the Best Parameters ==============================================
| Rank Test Score | Params | Train Score | Test Score | Fit Time |
|---|---|---|---|---|
| 1 | n_estimators: 100, max_leaf_nodes: None, loss: exponential, learning_rate: 1.0 | 1.00e+00 ± 6.11e-04 | 7.80e-01 ± 1.21e-02 | 7.73e-02 ± 6.73e-03 |
| 2 | n_estimators: 200, max_leaf_nodes: 3, loss: exponential, learning_rate: 1.0 | 9.66e-01 ± 5.98e-03 | 7.80e-01 ± 1.49e-02 | 1.10e-01 ± 2.07e-03 |
| 3 | n_estimators: 200, max_leaf_nodes: None, loss: deviance, learning_rate: 1.0 | 1.00e+00 ± 0.00e+00 | 7.79e-01 ± 1.78e-02 | 1.45e-01 ± 2.55e-03 |
| 4 | n_estimators: 200, max_leaf_nodes: None, loss: deviance, learning_rate: 0.8 | 1.00e+00 ± 0.00e+00 | 7.78e-01 ± 1.12e-02 | 1.46e-01 ± 3.03e-03 |
| 5 | n_estimators: 100, max_leaf_nodes: None, loss: deviance, learning_rate: 1.0 | 1.00e+00 ± 0.00e+00 | 7.78e-01 ± 1.92e-02 | 7.40e-02 ± 2.07e-03 |
| 6 | n_estimators: 100, max_leaf_nodes: None, loss: exponential, learning_rate: 0.9 | 9.99e-01 ± 1.19e-03 | 7.77e-01 ± 1.60e-02 | 7.41e-02 ± 1.75e-03 |
| 7 | n_estimators: 200, max_leaf_nodes: None, loss: exponential, learning_rate: 1.0 | 1.00e+00 ± 0.00e+00 | 7.77e-01 ± 1.46e-02 | 1.51e-01 ± 6.23e-03 |
| 8 | n_estimators: 100, max_leaf_nodes: None, loss: deviance, learning_rate: 0.9 | 1.00e+00 ± 0.00e+00 | 7.76e-01 ± 1.49e-02 | 8.09e-02 ± 6.05e-03 |
| 9 | n_estimators: 100, max_leaf_nodes: None, loss: deviance, learning_rate: 0.8 | 1.00e+00 ± 4.44e-04 | 7.76e-01 ± 9.68e-03 | 7.49e-02 ± 1.26e-03 |
| 10 | n_estimators: 100, max_leaf_nodes: None, loss: exponential, learning_rate: 0.8 | 9.98e-01 ± 1.81e-03 | 7.76e-01 ± 1.26e-02 | 8.14e-02 ± 7.63e-03 |
| 11 | n_estimators: 100, max_leaf_nodes: 3, loss: exponential, learning_rate: 0.8 | 8.96e-01 ± 6.76e-03 | 7.76e-01 ± 1.05e-02 | 5.79e-02 ± 2.79e-03 |
| 12 | n_estimators: 100, max_leaf_nodes: 3, loss: exponential, learning_rate: 1.0 | 9.09e-01 ± 8.38e-03 | 7.75e-01 ± 1.09e-02 | 5.75e-02 ± 2.65e-03 |
| 13 | n_estimators: 200, max_leaf_nodes: 2, loss: deviance, learning_rate: 1.0 | 8.36e-01 ± 8.70e-03 | 7.75e-01 ± 1.21e-02 | 9.53e-02 ± 1.90e-03 |
| 14 | n_estimators: 100, max_leaf_nodes: 2, loss: deviance, learning_rate: 0.9 | 8.16e-01 ± 8.18e-03 | 7.75e-01 ± 1.71e-02 | 5.36e-02 ± 3.97e-03 |
| 15 | n_estimators: 200, max_leaf_nodes: None, loss: exponential, learning_rate: 0.9 | 1.00e+00 ± 0.00e+00 | 7.75e-01 ± 1.71e-02 | 1.46e-01 ± 1.86e-03 |
| 16 | n_estimators: 1000, max_leaf_nodes: None, loss: exponential, learning_rate: 0.9 | 1.00e+00 ± 0.00e+00 | 7.74e-01 ± 1.62e-02 | 7.26e-01 ± 4.01e-03 |
| 17 | n_estimators: 200, max_leaf_nodes: 2, loss: deviance, learning_rate: 0.8 | 8.27e-01 ± 7.57e-03 | 7.74e-01 ± 1.61e-02 | 1.04e-01 ± 7.32e-03 |
| 18 | n_estimators: 1000, max_leaf_nodes: None, loss: deviance, learning_rate: 1.0 | 1.00e+00 ± 0.00e+00 | 7.74e-01 ± 1.37e-02 | 7.09e-01 ± 3.24e-03 |
| 19 | n_estimators: 200, max_leaf_nodes: None, loss: exponential, learning_rate: 0.8 | 1.00e+00 ± 0.00e+00 | 7.73e-01 ± 1.35e-02 | 1.57e-01 ± 1.02e-02 |
| 20 | n_estimators: 100, max_leaf_nodes: 3, loss: exponential, learning_rate: 0.9 | 9.04e-01 ± 8.17e-03 | 7.73e-01 ± 1.18e-02 | 5.89e-02 ± 4.54e-03 |
Since we have identified the best parameters for our modeling, we train another model using these parameters.
Header('Gradient Boosting Classifier with the Best Parameters')
GBC = GradientBoostingClassifier(**grid.best_params_)
print('Default Parameters = %s' % GBC.get_params(deep=True))
_ = GBC.fit(X_train, y_train)
Reports_Train, Reports_Test, CM_Train, CM_Test = Stratified_CV_Scoring(GBC, X = X, y = y, n_splits = 20)
display(Reports_Train.style.hide_index().set_properties(**{'background-color': 'HoneyDew', 'color': 'Black'}).\
set_properties(subset=['Train Set (CV = % i)' % n_splits], **{'background-color': 'DarkGreen', 'color': 'White'}))
display(Reports_Test.style.hide_index().set_properties(**{'background-color': 'Azure', 'color': 'Black'}).\
set_properties(subset=['Test Set (CV = % i)' % n_splits], **{'background-color': 'MediumBlue', 'color': 'White'}))
Confusion_Mat(CM_Train, CM_Test, n_splits = 20)
Header('Train Set', C = 'Green')
tn, fp, fn, tp = CM_Train.ravel()
Precision = tp/(tp+fp)
Recall = tp/(tp + fn)
TPR = tp/(tp +fn)
TNR = tn/(tn +fp)
BA = (TPR + TNR)/2
print('Precision (Train) = %.2f' % Precision)
print('Recall (Train) = %.2f' % Recall)
print('TPR (Train) = %.2f' % TPR)
print('TNR (Train) = %.2f' % TNR)
print('Balanced Accuracy (Train) = %.2f' % BA)
Header('Test Set')
tn, fp, fn, tp = CM_Test.ravel()
Precision = tp/(tp+fp)
Recall = tp/(tp + fn)
TPR = tp/(tp +fn)
TNR = tn/(tn +fp)
BA = (TPR + TNR)/2
PPCR = (tp + fp)/(tp + fp + tn+ fn)
print('Precision (Test) = %.2f' % Precision)
print('Recall (Test) = %.2f' % Recall)
print('TPR (Test) = %.2f' % TPR)
print('TNR (Test) = %.2f' % TNR)
print('Balanced Accuracy (Test) = %.2f' % BA)
del tn, fp, fn, tp, Precision, Recall, TPR, TNR, BA
Line()
Gradient Boosting Classifier with the Best Parameters ============================================== Default Parameters = {'ccp_alpha': 0.0, 'criterion': 'friedman_mse', 'init': None, 'learning_rate': 1.0, 'loss': 'exponential', 'max_depth': 3, 'max_features': None, 'max_leaf_nodes': None, 'min_impurity_decrease': 0.0, 'min_impurity_split': None, 'min_samples_leaf': 1, 'min_samples_split': 2, 'min_weight_fraction_leaf': 0.0, 'n_estimators': 100, 'n_iter_no_change': None, 'random_state': None, 'subsample': 1.0, 'tol': 0.0001, 'validation_fraction': 0.1, 'verbose': 0, 'warm_start': False}
| Train Set (CV = 20) | precision | recall | f1-score | support |
|---|---|---|---|---|
| Bad | 1.0000 ± 0.0000 | 0.9995 ± 0.0014 | 0.9998 ± 0.0007 | 210.0000 ± 0.0000 |
| Good | 0.9998 ± 0.0006 | 1.0000 ± 0.0000 | 0.9999 ± 0.0003 | 490.0000 ± 0.0000 |
| accuracy | 0.9999 ± 0.0004 | 0.9999 ± 0.0004 | 0.9999 ± 0.0004 | 0.9999 ± 0.0004 |
| macro avg | 0.9999 ± 0.0003 | 0.9998 ± 0.0007 | 0.9998 ± 0.0005 | 700.0000 ± 0.0000 |
| weighted avg | 0.9999 ± 0.0004 | 0.9999 ± 0.0004 | 0.9999 ± 0.0004 | 700.0000 ± 0.0000 |
| Test Set (CV = 20) | precision | recall | f1-score | support |
|---|---|---|---|---|
| Bad | 0.5109 ± 0.0369 | 0.4761 ± 0.0403 | 0.4915 ± 0.0286 | 90.0000 ± 0.0000 |
| Good | 0.7816 ± 0.0119 | 0.8029 ± 0.0314 | 0.7918 ± 0.0169 | 210.0000 ± 0.0000 |
| accuracy | 0.7048 ± 0.0199 | 0.7048 ± 0.0199 | 0.7048 ± 0.0199 | 0.7048 ± 0.0199 |
| macro avg | 0.6463 ± 0.0224 | 0.6395 ± 0.0193 | 0.6416 ± 0.0200 | 300.0000 ± 0.0000 |
| weighted avg | 0.7004 ± 0.0173 | 0.7048 ± 0.0199 | 0.7017 ± 0.0178 | 300.0000 ± 0.0000 |
Train Set ========================================================================================== Precision (Train) = 1.00 Recall (Train) = 1.00 TPR (Train) = 1.00 TNR (Train) = 1.00 Balanced Accuracy (Train) = 1.00 Test Set =========================================================================================== Precision (Test) = 0.78 Recall (Test) = 0.80 TPR (Test) = 0.80 TNR (Test) = 0.48 Balanced Accuracy (Test) = 0.64 ====================================================================================================